package com.ruoyi.web.controller.app;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.entity.SysAssessment;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.service.IAppUserService;
import com.ruoyi.system.service.ISysAssessmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/app/user")
public class AppUserController extends BaseController {


    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private ISysAssessmentService assessmentService;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:appuser:list')")
    @GetMapping("/list")
    public TableDataInfo list(AppUser appUser) {
        startPage();
        List<AppUser> appUserList = appUserService.selectUserList(appUser);
        return getDataTable(appUserList);
    }

    @PreAuthorize("@ss.hasPermi('system:appuser:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId))
        {
            AppUser appUser = appUserService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, appUser);
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:appuser:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody AppUser user)
    {
        if (StringUtils.isNotNull(user.getMainRehThe()) && StringUtils.isNotNull(user.getSpareRehThe())) {
            if (user.getMainRehThe().equals(user.getSpareRehThe())) {
                return error("主康复师与副康复师不能一样");
            }
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(appUserService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:appuser:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody AppUser user)
    {
        if (StringUtils.isNotNull(user.getMainRehThe()) && StringUtils.isNotNull(user.getSpareRehThe())) {
            if (user.getMainRehThe().equals(user.getSpareRehThe())) {
                return error("主康复师与副康复师不能一样");
            }
        }
        user.setUpdateBy(getUsername());
        return toAjax(appUserService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:appuser:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(appUserService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:appuser:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody AppUser user)
    {
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(appUserService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:appuser:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody AppUser user)
    {
        user.setUpdateBy(getUsername());
        return toAjax(appUserService.updateUserStatus(user));
    }

    /**
     * 上传模板
     */
    @PreAuthorize("@ss.hasPermi('system:appuser:import')")
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);

            // 判断之前是否上传过模板，如果上传过模板，则删除之前的模板
            SysAssessment isExistSysAssessment = assessmentService.templateIsExist();
            if (isExistSysAssessment != null) {
                assessmentService.deleteTemplate();
            }
            String url = serverConfig.getUrl() + fileName;
            // 插入模板数据
            SysAssessment sysAssessment = new SysAssessment();
            sysAssessment.setCreateBy(getUsername());
            sysAssessment.setIsTemplate("0");
            sysAssessment.setAssessmentUrl(url);
            assessmentService.insert(sysAssessment);

            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 上传评估结果
     */
    @PreAuthorize("@ss.hasPermi('system:appuser:importAssessment')")
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importAssessment")
    public AjaxResult uploadAssessmentFile(MultipartFile file,Long userId) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            // 判断之前用户是否上传过评估结果，如果有，则直接删除
            SysAssessment isExistSysAssessment = assessmentService.selectAssessmentByUserId(userId);
            if (isExistSysAssessment != null) {
                assessmentService.deleteAssessmentByUserId(userId);
            }
            String url = serverConfig.getUrl() + fileName;

            // 插入模板数据
            SysAssessment sysAssessment = new SysAssessment();
            sysAssessment.setCreateBy(getUsername());
            sysAssessment.setIsTemplate("1");
            sysAssessment.setAssessmentUrl(url);
            sysAssessment.setUserId(userId);
            assessmentService.insert(sysAssessment);

            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

}
